package cn.edu.zxj.springblog.config;

import cn.edu.zxj.springblog.utils.JWTUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created with IntelliJ IDEA.
 * Description：登录拦截器
 *
 * @author: zxj
 * @date: 2024-02-04
 * @time: 23:45:34
 */
@Configuration
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("正在进行登录拦截校验...");

        // 1. 从 header 中获得 token
        String token = request.getHeader("user_token");

        log.info("从 request 中获得 token: {}",token);

        // 2. 验证 token
        Claims claims = JWTUtils.parseJWT(token);

        if (claims == null) {
            // 该 token 是不合法的, 未登录状态, 不放行
            response.setStatus(401);
            log.info("用户未登录, 登录拦截");
            return false;
        }

        // 走到这里, token 合法, 放行
        log.info("用户登录, 放行");
        return true;
    }
}
